// 导入模块
import axios from 'axios'
import router from '@/router'
import Vue from 'vue'
import { Toast } from 'vant'
Vue.use(Toast)

let AUTH_TOKEN = ''

// 全局配置 Config Defaults
// axios.defaults.baseURL = "http://localhost:3000"; //基路径

// 与token有关的请求头  配置了默认请求头对卖座有影响(不要用默认)
// axios.defaults.headers.common.Authorization = AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 拦截器配置 .. Interceptors
// Add a request interceptor 发送请求之前
axios.interceptors.request.use(function (config) {
  // config.baseURL = 'http://47.93.55.54:3000/'

  // 把sessionStorage中的token放到config.headers['Authorization']中就完成了前端的任务
  if (sessionStorage.userInfo) {
    AUTH_TOKEN = JSON.parse(sessionStorage.userInfo).token
  }
  config.headers.Authorization = AUTH_TOKEN
  // Do something before request is sent

  // console.log(config)
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor 响应数据之后
axios.interceptors.response.use(function (response) {
  // Do something with response data

  // 如果都是token有问题的,跳转到登录页
  if (response.data.code === '500') {
    // localStorage.clear();//退出登录 删除localStorage
    Toast.fail(response.data.msg)
    sessionStorage.removeItem('userInfo')
    router.push({ name: 'User-type', params: { type: 'login' } })
  }
  // console.log(response)
  return response
}, function (error) {
  // Do something with response error
  return Promise.reject(error)
})

// 导出
export default axios
